const temples = {
  root: children => children,
  h3: (children, index) => <h3 key={index}>{children}</h3>,
  p: (children, index) => <p key={index}>{children}</p>,
};

export const parseMessage = function parseMessage(message) {
  if (!message) return '';

  const parser = new DOMParser();
  const xmldom = parser.parseFromString(`<root>${message}</root>`, 'text/xml');
  let index = 1;

  const replacer = (preNodes, curNode) => {
    const isElement = Node.ELEMENT_NODE === curNode.nodeType;
    const isText = Node.TEXT_NODE === curNode.nodeType;
    const hasChild = curNode.hasChildNodes();

    if (isElement) {
      const children = hasChild ? [].reduce.call(curNode.childNodes, replacer, []) : [];
      return preNodes.concat(
        temples[curNode.nodeName] ? [temples[curNode.nodeName](children, index++)] : [],
      );
    } else if (isText) {
      return preNodes.concat([curNode.nodeValue]);
    }
    return preNodes;
  };

  return replacer([], xmldom.childNodes[0]);
};
